package com.leyou.item.service;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.vo.PageResult;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.mapper.BrandMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
/**
 * 业务层代码
 */
@Service
@Transactional
public class BrandService {

    @Autowired
    private BrandMapper brandMapper;


    public PageResult<BrandDTO> brandPageQuery(String key, Integer page, Integer rows, String sortBy, Boolean desc) {
        //设置分页条件
        PageHelper.startPage(page, rows);
        //设置封装总对象
        Example example = new Example(Brand.class);
        //封装条件对象
        if(StringUtils.isNotBlank(key)){
            Example.Criteria criteria = example.createCriteria();
            criteria.orLike("name","%"+key+"%");
            criteria.orEqualTo("letter", key.toUpperCase());
        }
        //封装排序，使用的是原始的sql语句order by id desc
        example.setOrderByClause(sortBy+" "+(desc ? "DESC" : "ASC"));
        //分页查询
        List<Brand> brands = brandMapper.selectByExample(example);
        //判空
        if(CollectionUtils.isEmpty(brands)){
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        //得到PageHelper的分页对象
        PageInfo<Brand> pageInfo = new PageInfo<>(brands);
        //得到总记录数
        long total = pageInfo.getTotal();
        //得到BrandDTO的集合
        List<BrandDTO> brandDTOS = BeanHelper.copyWithCollection(pageInfo.getList(), BrandDTO.class);
        //创建自己的分页对象
        PageResult<BrandDTO> pageResult = new PageResult<>(total, brandDTOS);
        //返回
        return pageResult;
    }
}